package xcmg.device.service.marketing;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInfoDO;
import xcmg.device.dao.entity.marketing.MarketingActivityDO;
import xcmg.device.dao.entity.marketing.MarketingDealerDO;
import xcmg.device.dao.entity.marketing.MarketingDealerViewDO;
import xcmg.device.dao.entity.marketing.MarketingMaterialsDO;
import xcmg.device.dao.entity.marketing.PriceSearchReportDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInfoMapper;
import xcmg.device.dao.mapper.MarketingActivityMapper;
import xcmg.device.dao.mapper.MarketingDealerMapper;
import xcmg.device.dao.mapper.MarketingMaterialsMapper;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.infra.ConstantInfo;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.service.basic.DataDictionaryService;
import xcmg.device.service.company.CompanyInfoService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.basic.DataDictionaryVO;
import xcmg.device.service.vo.basic.MarketingMaterialsConditionVO;
import xcmg.device.service.vo.basic.MaterialsSearchVO;
import xcmg.device.service.vo.basic.MaterialsVO;
import xcmg.device.service.vo.basic.OemPriceSyncVO;
import xcmg.device.service.vo.company.CompanyDealerVO;
import xcmg.device.service.vo.marketing.MarketingActivityPriceVO;
import xcmg.device.service.vo.marketing.MarketingActivityVO;
import xcmg.device.service.vo.marketing.MarketingDealerAddVO;
import xcmg.device.service.vo.marketing.MarketingDealerInfoVO;
import xcmg.device.service.vo.marketing.MarketingDealerVO;
import xcmg.device.service.vo.marketing.MarketingDealerViewFilter;
import xcmg.device.service.vo.marketing.MarketingDealerViewVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsAddVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsInfoVO;
import xcmg.device.service.vo.marketing.MarketingMaterialsVO;
import xcmg.device.service.vo.marketing.SupplierPriceSchemeQeuryParamVO;
import xcmg.device.service.vo.marketing.SupplierPriceSchemeQueryResultVO;
import xcmg.device.util.CompanyUtil;
import xcmg.device.util.DecimalUtil;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by sqq on 2018/3/1.
 */
@Slf4j
@Service
public class  MarketingActivityService {

    @Autowired
    private MarketingActivityMapper marketingActivityMapper;

    @Autowired
    private MarketingDealerMapper marketingDealerMapper;

    @Autowired
    private MarketingMaterialsMapper marketingMaterialsMapper;

    @Autowired
    private PriMaterialsMapper priMaterialsMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private CompanyUtil companyUtil;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private CompanyInfoMapper companyInfoMapper;


    @Value("${spring.file.download.path}")
    private String filePath;

    /**
     * excel模板文件名
     */
    private static final String MARKET_MATERIALS_TEMPLATE_FILE="MarketingMaterials.xls";

    /**
     * 进出口SAP CODE
     */
    public static final String SAP_CODE = "4060";

    /**
     * 0：指定折扣，1：指定价格
     */
    private static final Integer MOTE_TYPE_RATE = 0, MOTE_TYPE_PRICE = 1;

    private static final String IS_RUN = "markert:activity:isrun";

    /**
     * 价格方案名称
     */
    private static final String SCHEME_NAME = "FANAME";

    /**
     * 代理商含税销售价
     */
    private static final String DEALER_PRICE = "DLJ";

    /**
     * 直投促销价
     */
    private static final String DIRECT_PRICE = "DIRECT_PRICE";



    /**
     * 服务含税销售价
     */
    private static final String SERVICE_PRICE = "FWJ";

    @Autowired
    private DataDictionaryService dataDictionaryService;

    public List<MarketingActivityVO> list(String orgId) {
        MarketingActivityVO marketingActivityVO = new MarketingActivityVO();
        marketingActivityVO.setOrgId(orgId);
        PageHelperPlus.orderBy("create_date desc");
        List<MarketingActivityDO> marketingActivityDOList = marketingActivityMapper.list(marketingActivityVO);
        List<MarketingActivityVO> results = new ArrayList<>();
        for (MarketingActivityDO marketingActivityDO : marketingActivityDOList) {
            MarketingActivityVO marketingActivityVO1 = new MarketingActivityVO();
            BeanUtils.copyProperties(marketingActivityDO, marketingActivityVO1);
            results.add(marketingActivityVO1);
        }
        return results;
    }

    public List<MarketingActivityVO> enableList(Integer state, String orgId) {
        MarketingActivityVO marketingActivityVO = new MarketingActivityVO();
        marketingActivityVO.setOrgId(orgId);
        marketingActivityVO.setState(state);
        PageHelperPlus.orderBy("create_date desc");
        List<MarketingActivityDO> marketingActivityDOList = marketingActivityMapper.list(marketingActivityVO);
        List<MarketingActivityVO> results = new ArrayList<>();
        for (MarketingActivityDO marketingActivityDO : marketingActivityDOList
                ) {
            MarketingActivityVO marketingActivityVO1 = new MarketingActivityVO();
            BeanUtils.copyProperties(marketingActivityDO, marketingActivityVO1);
            results.add(marketingActivityVO1);
        }
        return results;
    }


    public ErrorCode add(MarketingActivityVO marketingActivityVO) {
        Integer nextSeq  = marketingActivityMapper.nextSeq();
        String activityId = nextSeq.toString();
        marketingActivityVO.setId(activityId);
        marketingActivityVO.setCreateDate(new Date());
        marketingActivityVO.setIsBuiltIn(false);
        MarketingActivityDO marketingActivityDO = new MarketingActivityDO();
        BeanUtils.copyProperties(marketingActivityVO, marketingActivityDO);

        Integer nameCount=marketingActivityMapper.nameCount(marketingActivityDO);
        if(nameCount>0){
            return ErrorCode.AcivityNameDuplicated;
        }
        if(!StringUtil.isNullOrEmpty(marketingActivityDO.getPriceGroup())){
            nameCount=marketingActivityMapper.nameCountPirceGroup(marketingActivityDO);
            if(nameCount>0){
                return ErrorCode.AcivityPriceGroupDuplicated;
            }
        }
        return marketingActivityMapper.insert(marketingActivityDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public ErrorCode update(MarketingActivityVO marketingActivityVO) {
        MarketingActivityDO marketingActivityDO = new MarketingActivityDO();
        Integer modeType = marketingActivityVO.getModeType();
        if(modeType != null && modeType.compareTo(1) == 0){ //如果时指定价格的，则不能配置为所有零件适用，此处手动设置 所有零件适用属性为false
           marketingActivityVO.setIsAllMaterials(0);
        }
        BeanUtils.copyProperties(marketingActivityVO, marketingActivityDO);
        MarketingActivityDO markDO=marketingActivityMapper.item(marketingActivityDO.getId());
        if(markDO==null){
            return ErrorCode.AcivityNotFound;
        }
        markDO.setName(marketingActivityDO.getName());
        Integer nameCount=marketingActivityMapper.nameCount(markDO);
        if(nameCount>0){
            return ErrorCode.AcivityNameDuplicated;
        }
        if(!StringUtil.isNullOrEmpty(marketingActivityDO.getPriceGroup())) {
            nameCount = marketingActivityMapper.nameCountPirceGroup(marketingActivityDO);
            if (nameCount > 0) {
                return ErrorCode.AcivityPriceGroupDuplicated;
            }
        }
        return marketingActivityMapper.update(marketingActivityDO) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    @Transactional
    public ErrorCode remove(String id) {
        marketingDealerMapper.deleteByActivityId(id);
        marketingMaterialsMapper.deleteByActivityId(id);
        return marketingActivityMapper.deleteByPrimaryKey(id) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public PageCommonVO marketingDealerViewList(SearchCommonVO<MarketingDealerViewFilter> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("create_date desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MarketingDealerViewDO> marketingDealerViewDOList = marketingDealerMapper.marketingDealerViewList(condition.getFilters());
        List<MarketingDealerViewVO> results = new ArrayList<>();
        for (MarketingDealerViewDO marketingDealerViewDO : marketingDealerViewDOList
        ) {
            MarketingDealerViewVO marketingDealerViewVO = new MarketingDealerViewVO();
            BeanUtils.copyProperties(marketingDealerViewDO, marketingDealerViewVO);
            results.add(marketingDealerViewVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(marketingDealerViewDOList));
        pageCommonVO.setPageInfoList(results);
        return pageCommonVO;
    }

    public List<MarketingDealerVO> marketingDealerList(String orgId, String activityId) {
        List<MarketingDealerDO> doList = marketingDealerMapper.list(orgId, activityId);
        List<MarketingDealerVO> voList = new ArrayList<>();
        for (MarketingDealerDO marketingDealerDO : doList
                ) {
            MarketingDealerVO marketingDealerVO = new MarketingDealerVO();
            BeanUtils.copyProperties(marketingDealerDO, marketingDealerVO);
            marketingDealerVO.setCompanyName(marketingDealerDO.getDealerOrgName());
            voList.add(marketingDealerVO);
        }
        return voList;
    }

    @Transactional
    public ErrorCode addDealer(MarketingDealerAddVO marketingDealerAddVO, String orgId) {
        marketingDealerMapper.deleteByActivityId(marketingDealerAddVO.getActivityId());
        for (MarketingDealerInfoVO info : marketingDealerAddVO.getDealerList()
        ) {
            ActionResult<String> textResult = fastGenClient.textGuid();
            if (textResult.getCode() != ErrorCode.Success.getCode()) {
                return ErrorCode.IllegalArument;
            }
            MarketingDealerDO marketingDealerDO = new MarketingDealerDO();
            marketingDealerDO.setId(textResult.getValue());
            marketingDealerDO.setActivityId(marketingDealerAddVO.getActivityId());
            marketingDealerDO.setDealerOrgId(info.getDealerOrgId());
            marketingDealerDO.setDealerOrgName(info.getCompanyName());
            marketingDealerDO.setCreateDate(new Date());
            marketingDealerDO.setOrgId(orgId);
            marketingDealerMapper.insert(marketingDealerDO);
        }
        return ErrorCode.Success;
    }

    public ErrorCode saveOrRemoveDealer(MarketingDealerAddVO marketingDealerAddVO, String orgId) {
        if (CollectionUtils.isNotEmpty(marketingDealerAddVO.getDealerList())) {
            for (MarketingDealerInfoVO info : marketingDealerAddVO.getDealerList()) {
                ActionResult<String> textResult = fastGenClient.textGuid();
                if (textResult.getCode() != ErrorCode.Success.getCode()) {
                    return ErrorCode.IllegalArument;
                }
                MarketingDealerDO marketingDealerDO = new MarketingDealerDO();
                marketingDealerDO.setId(textResult.getValue());
                marketingDealerDO.setActivityId(marketingDealerAddVO.getActivityId());
                marketingDealerDO.setDealerOrgId(info.getDealerOrgId());
                marketingDealerDO.setDealerOrgName(info.getCompanyName());
                marketingDealerDO.setCreateDate(new Date());
                marketingDealerDO.setOrgId(orgId);
                marketingDealerMapper.insert(marketingDealerDO);
            }
        }

        if (CollectionUtils.isNotEmpty(marketingDealerAddVO.getRemoveList())) {
            marketingDealerMapper.deleteByIds(marketingDealerAddVO.getRemoveList());
        }

        return ErrorCode.Success;
    }

    public PageCommonVO<MaterialsVO> marketingMaterialsList(SearchCommonVO<MaterialsSearchVO> condition, String orgId) {
        PageCommonVO<MaterialsVO> result = new PageCommonVO<>();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<MaterialsVO> resultList = new ArrayList<>();
        if(!StringUtils.isEmpty(condition.getFilters().getMaterialsNos())){
            String splitString=",";
            if(condition.getFilters().getMaterialsNos().trim().contains("\n")){
                splitString="\n";
            }
            String[] str = condition.getFilters().getMaterialsNos().trim().replace("，", ",").split(splitString);
            condition.getFilters().setMaterialsList(Arrays.asList((str)));
        }
        if (!StringUtils.isEmpty(condition.getFilters().getCustomMaterialsNos())) {
            String[] str = condition.getFilters().getCustomMaterialsNos().trim().replace("，", ",").split(",");
            condition.getFilters().setCustomMaterialsList(Arrays.asList((str)));
        }
        PageHelperPlus.orderBy("create_date desc");
        resultList = priMaterialsMapper.list(condition.getFilters());
        for (MaterialsVO model : resultList) {
            takeDecimals(model);
            List<MarketingMaterialsVO> voList = marketingMaterialsMapper.materialsList(orgId, model.getMaterialsNo());
            model.setMarketingMaterialsList(voList);
        }
        result.setPageInfo(new PageInfo(resultList));
        result.setPageInfoList(resultList);
        return result;
    }

    private static void takeDecimals(MaterialsVO model) {
        if (model.getStandardPrice() != null) {
            model.setStandardPrice(model.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getPrice() != null) {
            model.setPrice(model.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
        if (model.getMovingAveragePrice() != null) {
            model.setMovingAveragePrice(model.getMovingAveragePrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
        }
    }

    public ErrorCode saveMarketingMaterials(List<MarketingMaterialsAddVO> marketingMaterialsAddVOList, String orgId) {
        for (MarketingMaterialsAddVO marketingMaterialsAddVO : marketingMaterialsAddVOList
                ) {
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(marketingMaterialsAddVO.getMaterialsNo(), orgId);
            if (priMaterialsDO == null) {
                return ErrorCode.MaterialsNotExists;
            }
            for (MarketingMaterialsInfoVO info : marketingMaterialsAddVO.getMaterialsList()
                    ) {
                MarketingActivityDO marketingActivityDO = marketingActivityMapper.item(info.getActivityId());
                if (marketingActivityDO == null) {
                    return ErrorCode.AcivityNotFound;
                }
                MarketingMaterialsVO marketingMaterialsVO = marketingMaterialsMapper.itemByActivityMaterials(orgId, marketingMaterialsAddVO.getMaterialsNo(), info.getActivityId());
                MarketingMaterialsDO marketingMaterialsDO = new MarketingMaterialsDO();
                if (marketingMaterialsVO == null) {
                    if (!info.getChecked()) {
                        continue;
                    }
                    ActionResult<String> textResult = fastGenClient.textGuid();
                    if (textResult.getCode() != ErrorCode.Success.getCode()) {
                        return ErrorCode.IllegalArument;
                    }
                    marketingMaterialsDO.setId(textResult.getValue());
                    marketingMaterialsDO.setCreateDate(new Date());
                    marketingMaterialsDO.setActivityId(info.getActivityId());
                    marketingMaterialsDO.setMaterialsNo(priMaterialsDO.getMaterialsNo());
                    marketingMaterialsDO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
                    marketingMaterialsDO.setOrgId(orgId);
                    if(marketingActivityDO.getModeType().equals(1)){
                    marketingMaterialsDO.setPrice(info.getPrice().multiply(new BigDecimal("100")));
                    }
                    marketingMaterialsMapper.insert(marketingMaterialsDO);
                } else {
                    if (!info.getChecked()) {
                        marketingMaterialsMapper.deleteByPrimaryKey(marketingMaterialsVO.getId());
                        continue;
                    }
                    BeanUtils.copyProperties(marketingMaterialsVO, marketingMaterialsDO);
                    if(marketingActivityDO.getModeType().equals(1)) {
                        marketingMaterialsDO.setPrice(info.getPrice().multiply(new BigDecimal("100")));
                    }
                    marketingMaterialsMapper.update(marketingMaterialsDO);
                }
            }
        }
        return ErrorCode.Success;
    }

    public List<MarketingActivityPriceVO> activityPriceList(String dealerOrgId, String orgId, String materialsNo) throws Exception{
        PriMaterialsDO priMaterialsDO=priMaterialsMapper.itemByNo(materialsNo,orgId);
        if(priMaterialsDO == null ){
            return new ArrayList<>();
        }
        //查询当前账号类型
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByPlatOrgId(dealerOrgId);
        //获取默认价格方案名称
        DataDictionaryVO dictVO = getDefaultSchemaName(companyDealerDO,null);
        String schemaName = null == dictVO ? "" : dictVO.getName();
        List<MarketingActivityPriceVO> priceList = marketingActivityMapper.activityList4Default(dealerOrgId,
                orgId, materialsNo, schemaName);
        for (MarketingActivityPriceVO info:priceList) {
            if(info.getModeType()==1){
                info.setDiscountPrice(info.getPrice());
            }else {
                BigDecimal disPrice = new BigDecimal(0);
                // 价格类型为空，则调整后价格=销售价*折扣
                if (ObjectUtils.isEmpty(info.getPriceType())){
                    if(priMaterialsDO.getPrice() == null) {
                        StringBuffer desBuffer = new StringBuffer();
                        desBuffer.append("零件号").append(priMaterialsDO.getMaterialsNo()).append("没有价格");
                        throw new Exception(desBuffer.toString());
                    }
                    disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 价格类型为销售价，则调整后价格=销售价*折扣
                if (!ObjectUtils.isEmpty(info.getPriceType()) && info.getPriceType().equals(ConstantInfo.PRICE_TYPE_SALE)) {
                    if(priMaterialsDO.getPrice() == null) {
                        StringBuffer desBuffer = new StringBuffer();
                        desBuffer.append("零件号").append(priMaterialsDO.getMaterialsNo()).append("没有价格");
                        throw new Exception(desBuffer.toString());
                    }
                    disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
                // 价格类型为标准价，则调整后价格=标准价*折扣
                if (!ObjectUtils.isEmpty(info.getPriceType()) && info.getPriceType().equals(ConstantInfo.PRICE_TYPE_STANDARD)){
                    if(priMaterialsDO.getPrice() == null) {
                        StringBuffer desBuffer = new StringBuffer();
                        desBuffer.append("零件号").append(priMaterialsDO.getMaterialsNo()).append("没有价格");
                        throw new Exception(desBuffer.toString());
                    }
                    disPrice = priMaterialsDO.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                }
                disPrice = disPrice.multiply(info.getModeRate());
                info.setDiscountPrice(disPrice);
            }
        }
        return priceList;
    }

    public List<MarketingActivityPriceVO> activityPriceVoList(String dealerOrgId, String orgId, String materialsNo){
      return marketingActivityMapper.activityList(dealerOrgId,orgId,materialsNo);
    }

    /** 
    * @Desc   多零件批量查询价格方案
    * @Author Mr.dong 
    * @Date   2021/5/28 16:19
    */ 
    public List<MarketingActivityPriceVO> activityPrice4Batch(String dealerOrgId, String orgId, List<String> materialsNos) throws Exception{
        List<PriMaterialsDO> priMaterialsDOS = priMaterialsMapper.selectByMaterialsNos(materialsNos, orgId);

        if (CollectionUtils.isEmpty(priMaterialsDOS)){
            return new ArrayList<>();
        }
        Map<String, PriMaterialsDO> priMaterialsDOMap = priMaterialsDOS.stream()
                .collect(Collectors.toMap(PriMaterialsDO::getMaterialsNo, Function.identity(), (k1,k2)->k2));
        List<MarketingActivityPriceVO> priceList = marketingActivityMapper.activityList4Batch(dealerOrgId, orgId, materialsNos);
        //遍历赋值
        if (CollectionUtils.isNotEmpty(priceList)){
            for (MarketingActivityPriceVO info : priceList) {
                String materialsNo = info.getMaterialsNo();
                if (info.getModeType() == 1){
                    info.setDiscountPrice(info.getPrice());
                } else {
                    PriMaterialsDO priMaterialsDO = new PriMaterialsDO();
                    if (priMaterialsDOMap.containsKey(materialsNo)){
                        priMaterialsDO = priMaterialsDOMap.get(materialsNo);
                    }
                    if(priMaterialsDO.getPrice() == null) {
                        throw new Exception("零件号"+ materialsNo +"没有价格");
                    }
                    BigDecimal disPrice = new BigDecimal(0);

                    // 价格类型为标准价，则调整后价格=标准价*折扣
                    if (!ObjectUtils.isEmpty(info.getPriceType()) && info.getPriceType().equals(ConstantInfo.PRICE_TYPE_STANDARD)){
                        disPrice = priMaterialsDO.getStandardPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    } else {//价格类型为空，或者价格类型为销售价 则调整后价格=销售价*折扣
                        disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    }
                    disPrice = disPrice.multiply(info.getModeRate());
                    info.setDiscountPrice(disPrice);
                }
            }
        }

        return priceList;
    }

    public MarketingActivityPriceVO activityPriceModel(String dealerOrgId, String orgId, String materialsNo){
        PriMaterialsDO priMaterialsDO=priMaterialsMapper.itemByNo(materialsNo,orgId);
        if(priMaterialsDO==null){
            return null;
        }
        CompanyDealerDO companyDealerDO=companyDealerMapper.itemByOrgId(orgId,dealerOrgId);

        return activityPriceModel(companyDealerDO, orgId, materialsNo);
    }

    public MarketingActivityPriceVO activityPriceModel(CompanyDealerDO companyDealerDO, String orgId, String materialsNo){

        if(companyDealerDO==null|| StringUtil.isNullOrEmpty(companyDealerDO.getPriceGroup())){
            return null;
        }
        MarketingActivityPriceVO priceInfo=marketingActivityMapper.activityModel(companyDealerDO.getDealerOrgId(),orgId,materialsNo,companyDealerDO.getPriceGroup());
        if(priceInfo==null){
            if(!companyDealerDO.getIsPlatCompany()){
                return null;
            }
            else{
                priceInfo=marketingActivityMapper.activityModel(companyDealerDO.getPlatOrgId(),orgId,materialsNo,companyDealerDO.getPriceGroup());
                if(priceInfo==null){
                    return null;
                }
            }
        }
        if(priceInfo.getModeType()==1){
            priceInfo.setDiscountPrice(priceInfo.getPrice());
        }else {
            PriMaterialsDO priMaterialsDO=priMaterialsMapper.itemByNo(materialsNo,orgId);
            if(priMaterialsDO==null){
                return null;
            }
            BigDecimal disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
            disPrice = disPrice.multiply(priceInfo.getModeRate());
            priceInfo.setDiscountPrice(disPrice);
        }
        return priceInfo;
    }

    
    public MarketingActivityVO getDefaultMarketingActivity(String receiveOrgId, String supplierOrgId) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(supplierOrgId, receiveOrgId);
        //获取默认价格方案名称
        DataDictionaryVO dictVO = getDefaultSchemaName(companyDealerDO, null);
        if (dictVO == null) {
            return null;
        }
        MarketingActivityDO activityDO = marketingActivityMapper.activityByName(companyUtil.ynOrgId(), dictVO.getName());
        if (activityDO == null) {
            return null;
        }
        MarketingActivityVO activityVO = new MarketingActivityVO();
        BeanUtils.copyProperties(activityDO, activityVO);
        return activityVO;
    }

    public MarketingActivityPriceVO activityPriceModelByName(CompanyDealerDO companyDealerDO, String orgId, String materialsNo, Boolean direct) {
        //获取默认价格方案名称
        DataDictionaryVO dictVO = getDefaultSchemaName(companyDealerDO, direct);
        if (dictVO == null) {
            return null;
        }
        MarketingActivityPriceVO priceInfo = marketingActivityMapper.activityModelByName(materialsNo, dictVO.getName());
        if (priceInfo == null) {
            return null;
        }

        if (priceInfo.getModeType().equals(MOTE_TYPE_PRICE)) {//指定价格
            priceInfo.setDiscountPrice(priceInfo.getPrice());
        } else {//固定折扣
            PriMaterialsDO priMaterialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
            if (priMaterialsDO == null) {
                return null;
            }
            BigDecimal disPrice = priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
            disPrice = disPrice.multiply(priceInfo.getModeRate());
            priceInfo.setDiscountPrice(disPrice);
        }
        return priceInfo;
    }

    /**
     * 获取默认价格方案名称
     *  1.一级代理商向云内提交的普通订单、直投订单，价格均取代理商含税销售价；
     *  2.二级代理商向云内提交的直发订单，价格取服务含税销售价；
     *  3.服务站向一级代理商提报的普通需求订单，价格取服务含税销售价
     * @param companyDealerDO
     * @return
     */
    private DataDictionaryVO getDefaultSchemaName(CompanyDealerDO companyDealerDO,Boolean direct) {
        if (null == companyDealerDO || null == companyDealerDO.getDealerType() || null == companyDealerDO.getDealerLevel()){
            return null;
        }
        String code = "";
        if (null != direct && direct) {
            code = DIRECT_PRICE;
        } else
        //一级代理商
        if (companyDealerDO.getDealerType() == 2 && companyDealerDO.getDealerLevel() == 1) {
            code = DEALER_PRICE;
        }
        //二级代理商或者服务站
        else if ((companyDealerDO.getDealerType() == 2 && companyDealerDO.getDealerLevel() == 2)
                || (companyDealerDO.getDealerType() == 5 && companyDealerDO.getDealerLevel() == 1)){
            code = SERVICE_PRICE;
        }
        DataDictionaryVO dictVO = dataDictionaryService.itemByCode(SCHEME_NAME, code);
        if (dictVO == null){
            return null;
        }
        return dictVO;
    }


//    /**
//     * @Author: WangKe
//     * @Description: 调用批量获取价格接口
//     * @Date: 2018/5/4 0004
//     */
//    @Async
//    public void synSap(String orgId, Integer type)throws Exception{
//        int isRun = NumberUtils.toInt(stringRedisTemplate.opsForValue().get(IS_RUN));
//        if(isRun == 1){
//            LogHelper.error("上次接口调用尚未结束", ErrorCode.RequestIdError.getCode());
//            return;
//        }
//        synchronized(this){
//            stringRedisTemplate.opsForValue().set(IS_RUN, "1", 10, TimeUnit.MINUTES);
//            try {
//                this.synSapFunc(orgId, type);
//            }catch (Exception e){
//                e.printStackTrace();
//            }finally {
//                stringRedisTemplate.delete(IS_RUN);
//            }
//            stringRedisTemplate.delete(IS_RUN);
//        }
//
//    }

//    /**
//     * @Author: WangKe
//     * @Description: 价格方案增量同步定时任务，每个企业单独一个线程执行
//     * @Date: 2019/1/9 0009
//     */
//    @Async
//    public void synSapTask(String orgId, String orgName, Integer type)throws Exception{
//        LogHelper.monitor("======执行开始，当前企业："+orgName+"======");
//        synSapFunc(orgId, type);
//        LogHelper.monitor("======执行结束，当前企业："+orgName+"======");
//    }
//
//    private void synSapFunc(String orgId, Integer type) throws Exception{
//        CompanyInfoVO companyInfoVO = companyInfoService.info(orgId);
//        //判断当前企业是否调用sap接口
//        if(companyInfoVO == null || companyInfoVO.getIsSap() == null || companyInfoVO.getIsSap() == 0){
//            LogHelper.error("当前企业不可调用SAP接口", ErrorCode.RequestIdError.getCode());
//            return;
//        }
//        ImportParam importParam = new ImportParam();
//        if(type == 0){
//            importParam.setFunction("ZPMS_PRD_GET_PRICE");
//        }else{
//            importParam.setFunction("ZPMS_PRD_GET_PRICENEW");
//        }
//        importParam.setTable("PRICE2INFO");
//
//        Map<String, String> commonMap = new HashMap<>();
//        commonMap.put("VKORG", companyInfoVO.getSapCode());
//        if(type == 1){
//            commonMap.put("I_PSTMP", nowTime());
//        }
//        importParam.setCommonParamMap(commonMap);
//        importParam.setSapCode(companyInfoVO.getSapCode());
//        LogHelper.monitor("========调用批量获取价格接口开始");
//        OutputParam outputParam = SAPCommonUtil.getData(importParam);
//        LogHelper.monitor("========调用批量获取价格接口结束");
//
//        if(outputParam == null || outputParam.getDataList() == null){
//            LogHelper.error("批量获取价格接口返回值为null", ErrorCode.RequestIdError.getCode());
//            throw new Exception("预留单过账sap返回值为null");
//        }
//        if(outputParam.getCode() == 1){
//            LogHelper.error("调用批量获取价格接口失败，"+outputParam.getErrorMsg(), ErrorCode.RequestIdError.getCode());
//            throw new Exception(outputParam.getErrorMsg());
//        }
//
//        if(type == 0){//删除之前数据
//            marketingActivityMapper.deleteForUpdate(orgId);
//            LogHelper.monitor("========价格方案删除结束========");
//            marketingMaterialsMapper.deleteForUpdate(orgId);
//            LogHelper.monitor("========价格方案与零件关系删除结束========");
//            marketingDealerMapper.deleteForUpdate(orgId);
//            LogHelper.monitor("========价格方案与客户关系删除结束========");
//        }
//
//        List<Map<String, String>> dataList = outputParam.getDataList();
//        List<MarketingActivityDO> marketingActivityDOList = new ArrayList<>();
//        List<MarketingMaterialsDO> marketingMaterialsDOList = new ArrayList<>();
//        List<MarketingDealerDO> marketingDealerDOList = new ArrayList<>();
//        Map<String, String> map1 = new HashMap<>();
//        Map<String, Integer> map2 = new HashMap<>();
//        String priceGroup;
//        MarketingActivityDO marketingActivityDO;
//        MarketingMaterialsDO marketingMaterialsDO;
//        List<CompanyDealerDO> companyDealerDOList;
//        MarketingDealerDO marketingDealerDO;
//        String materialNo;
//        for(Map<String, String> map : dataList){
//            if(!companyInfoVO.getSapCode().equals(map.get("VKORG"))){
//                continue;
//            }
//            priceGroup = map.get("KONDA");
//            materialNo = map.get("MATNR").replaceAll("^(0+)", "");
//
//            if(!map1.containsKey(priceGroup)){
//                marketingActivityDO = new MarketingActivityDO();
//                marketingActivityDO.setId(marketingActivityMapper.nextSeq()+"");
//                marketingActivityDO.setCreateDate(new Date());
//                marketingActivityDO.setIsBuiltIn(false);
//                marketingActivityDO.setName(priceGroup);
//                marketingActivityDO.setPriceGroup(priceGroup);
//                marketingActivityDO.setIsSynSap(1);
//                marketingActivityDO.setState(1);
//                marketingActivityDO.setModeType(1);
//                marketingActivityDO.setOrgId(orgId);
//                marketingActivityDOList.add(marketingActivityDO);
//                map1.put(priceGroup, marketingActivityDO.getId());
//            }
//
//
//            //更新价格方案与零件关系
//            if(!map2.containsKey(priceGroup+"&&"+materialNo)){
//                marketingMaterialsDO = new MarketingMaterialsDO();
//                marketingMaterialsDO.setActivityId(map1.get(priceGroup));
//                marketingMaterialsDO.setCreateDate(new Date());
//                marketingMaterialsDO.setMaterialsNo(materialNo);
//                marketingMaterialsDO.setOrgId(orgId);
//                marketingMaterialsDO.setPriceGroup(priceGroup);
//                marketingMaterialsDO.setPrice(new BigDecimal(map.get("KBETR")).multiply(new BigDecimal("100")));
//                marketingMaterialsDOList.add(marketingMaterialsDO);
//                map2.put(priceGroup+"&&"+materialNo, 1);
//            }
//
//        }
//
//        //更新价格方案与客户关系
//        if(!ListUtil.isNullOrEmpty(marketingActivityDOList)){
//            for(MarketingActivityDO activityDO : marketingActivityDOList){
//                companyDealerDOList = companyDealerMapper.findByPriceGroup(orgId, activityDO.getPriceGroup());
//                if(!ListUtil.isNullOrEmpty(companyDealerDOList)){
//                    for(CompanyDealerDO dealerDO : companyDealerDOList){
//                        marketingDealerDO = new MarketingDealerDO();
//                        marketingDealerDO.setActivityId(activityDO.getId());
//                        marketingDealerDO.setCreateDate(new Date());
//                        marketingDealerDO.setDealerOrgId(dealerDO.getDealerOrgId());
//                        marketingDealerDO.setDealerOrgName(dealerDO.getCompanyName());
//                        marketingDealerDO.setOrgId(orgId);
//                        marketingDealerDO.setPriceGroup(activityDO.getPriceGroup());
//                        marketingDealerDOList.add(marketingDealerDO);
//                    }
//                }
//            }
//        }
//        LogHelper.monitor("========接口返回数据整合结束, sapCode: "+companyInfoVO.getSapCode()+"，价格方案实体数："+marketingActivityDOList.size()
//                +"，价格方案与零件关系实体数："+marketingMaterialsDOList.size()+"，价格方案与客户关系实体数："+marketingDealerDOList.size()+"========");
//
//        if(type == 0){
//            this.batchInsert(marketingActivityDOList, marketingMaterialsDOList, marketingDealerDOList);
//        }else{
//            this.batchIncrement(marketingActivityDOList, marketingMaterialsDOList, marketingDealerDOList, orgId);
//        }
//    }

    //批量插入
    private void batchInsert(List<MarketingActivityDO> marketingActivityDOList, List<MarketingMaterialsDO> marketingMaterialsDOList, List<MarketingDealerDO> marketingDealerDOList)throws Exception{
        if(!ListUtil.isNullOrEmpty(marketingActivityDOList)){
            LogHelper.monitor("========价格方案新增开始========");
            marketingActivityMapper.batchInsert(marketingActivityDOList);
            LogHelper.monitor("========价格方案新增结束========");
        }
        if(!ListUtil.isNullOrEmpty(marketingMaterialsDOList)){
            LogHelper.monitor("========价格方案与零件关系新增开始========");
            int times = marketingMaterialsDOList.size()/1000;
            int ot = marketingMaterialsDOList.size()%1000;
            for(int i=0; i<times; i++){
                marketingMaterialsMapper.batchInsert(marketingMaterialsDOList.subList(i*1000, (i+1)*1000));
            }
            if(ot > 0){
                marketingMaterialsMapper.batchInsert(marketingMaterialsDOList.subList(times*1000, marketingMaterialsDOList.size()));
            }
            LogHelper.monitor("========价格方案与零件关系新增结束========");
        }
        if(!ListUtil.isNullOrEmpty(marketingDealerDOList)){
            LogHelper.monitor("========价格方案与客户关系新增开始========");
            int times = marketingDealerDOList.size()/1000;
            int ot = marketingDealerDOList.size()%1000;
            for(int i=0; i<times; i++){
                marketingDealerMapper.batchInsert(marketingDealerDOList.subList(i*1000, (i+1)*1000));
            }
            if(ot > 0){
                marketingDealerMapper.batchInsert(marketingDealerDOList.subList(times*1000, marketingDealerDOList.size()));
            }
            LogHelper.monitor("========价格方案与客户关系新增结束========");
        }
    }

    //增量操作
    private void batchIncrement(List<MarketingActivityDO> marketingActivityDOList, List<MarketingMaterialsDO> marketingMaterialsDOList, List<MarketingDealerDO> marketingDealerDOList, String orgId)throws Exception{
        if(!ListUtil.isNullOrEmpty(marketingActivityDOList)){
            LogHelper.monitor("========价格方案新增开始========");
            MarketingActivityDO tempActivityDO;
            for(MarketingActivityDO activityDO : marketingActivityDOList){
                tempActivityDO = marketingActivityMapper.findByPriceGroup(orgId, activityDO.getPriceGroup());
                if(tempActivityDO == null){
                    marketingActivityMapper.insert(activityDO);
                }else{
                    tempActivityDO.setIsSynSap(1);
                    tempActivityDO.setUpdateDate(new Date());
                    marketingActivityMapper.update(tempActivityDO);
                }
            }
            LogHelper.monitor("========价格方案新增结束========");
        }
        if(!ListUtil.isNullOrEmpty(marketingMaterialsDOList)){
            LogHelper.monitor("========价格方案与零件关系新增开始========");
            MarketingMaterialsVO materialsVO;
            MarketingActivityDO tempActivityDO;
            for(MarketingMaterialsDO materialsDO : marketingMaterialsDOList){
                materialsVO = marketingMaterialsMapper.itemPriceGroup(orgId, materialsDO.getMaterialsNo(), materialsDO.getPriceGroup());
                if(materialsVO == null){
                    tempActivityDO = marketingActivityMapper.findByPriceGroup(orgId, materialsDO.getPriceGroup());
                    if(tempActivityDO == null){
                        continue;
                    }
                    materialsDO.setActivityId(tempActivityDO.getId());
                    marketingMaterialsMapper.insert(materialsDO);
                }else{
                    MarketingMaterialsDO tempMaterialsDO = new MarketingMaterialsDO();
                    BeanUtils.copyProperties(materialsVO, tempMaterialsDO);
                    tempMaterialsDO.setPrice(materialsDO.getPrice());
                    tempMaterialsDO.setUpdateDate(new Date());
                    marketingMaterialsMapper.update(tempMaterialsDO);
                }
            }
            LogHelper.monitor("========价格方案与零件关系新增结束========");
        }
        if(!ListUtil.isNullOrEmpty(marketingDealerDOList)){
            LogHelper.monitor("========价格方案与客户关系新增开始========");
            MarketingDealerDO dealer;
            MarketingActivityDO tempActivityDO;
            for(MarketingDealerDO dealerDO : marketingDealerDOList){
                dealer = marketingDealerMapper.itemPriceGroup(orgId, dealerDO.getDealerOrgId(), dealerDO.getPriceGroup());
                if(dealer == null){
                    tempActivityDO = marketingActivityMapper.findByPriceGroup(orgId, dealerDO.getPriceGroup());
                    if(tempActivityDO == null){
                        continue;
                    }
                    dealerDO.setActivityId(tempActivityDO.getId());
                    marketingDealerMapper.insert(dealerDO);
                }else{
                    MarketingDealerDO tempDealerDO = new MarketingDealerDO();
                    BeanUtils.copyProperties(dealer, tempDealerDO);
                    tempDealerDO.setUpdateDate(new Date());
                    marketingDealerMapper.update(tempDealerDO);
                }
            }
            LogHelper.monitor("========价格方案与客户关系新增结束========");
        }
    }

    //如果调用时间在凌晨需要把日期减一天
    private String nowTime(){
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String d = sdf.format(now);
        if("00:00:00".equals(d)){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DATE, -1);
            now = calendar.getTime();
        }
        sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(now);
    }

    public List<MarketingActivityVO> activityList(String orgId, String dealerOrgId){
        List<MarketingDealerDO> dealerDOList=marketingDealerMapper.dealerDOList(orgId,dealerOrgId);
        List<MarketingActivityVO> activityVOList=new ArrayList<>();
        if (CollectionUtils.isEmpty(dealerDOList)){
            return null;
        }
        for (MarketingDealerDO dealerDO:dealerDOList){
            MarketingActivityDO activityDo=marketingActivityMapper.activityDO(dealerDO.getOrgId(),dealerDO.getActivityId());
            MarketingActivityVO activityVO=new MarketingActivityVO();
            if(activityDo==null){
                continue;
            }
            BeanUtils.copyProperties(activityDo,activityVO);
            activityVOList.add(activityVO);
        }
        return activityVOList;
    }
    
    public boolean isSecondProxy(String orgId) {
        CompanyDealerDO dealerDO = companyDealerMapper.getDealerByPlatOrgId(companyUtil.ynOrgId(), orgId);
        if (dealerDO == null) {
            return true;
        } else {
            return false;
        }
    }

    public void exportAll(MaterialsSearchVO condition)throws Exception{
        String priceGroup = "";
        if (StringUtils.isNotBlank(condition.getPriceScheme())) {
            MarketingActivityDO marketingActivityDO = marketingActivityMapper.item(condition.getPriceScheme());
            if (marketingActivityDO != null) {
                priceGroup = marketingActivityDO.getPriceGroup();
            }
        }
        invokeExport(condition,priceGroup);
    }

    private void invokeExport(MaterialsSearchVO condition,String priceScheme) throws Exception {
        if (!StringUtils.isEmpty(condition.getMaterialsNos())) {
            String[] str = condition.getMaterialsNos().trim().replace("，", ",").split(",");
            condition.setMaterialsList(Arrays.asList((str)));
        }
        if (!StringUtils.isEmpty(condition.getCustomMaterialsNos())) {
            String[] str = condition.getCustomMaterialsNos().trim().replace("，", ",").split(",");
            condition.setCustomMaterialsList(Arrays.asList((str)));
        }

        String title = "设置零件价格数据导出";
        String priceColumnName = "进货基准价";
        //如果不是挖机，则不叫进货基准价，而是叫销售价
        String orgId = condition.getOrgId();
        if(!StringUtils.isEmpty(orgId)){
            CompanyInfoDO companyInfo = companyInfoMapper.item(orgId);
            if(companyInfo != null){
                String sapCode = companyInfo.getSapCode();
                boolean wjSapCode = CompanyUtil.isWJSapCode(sapCode);
                if(!wjSapCode){
                    priceColumnName = "销售价";
                }
            }
        }

        String[] rowsName;
        if (StringUtils.isNotBlank(priceScheme)) {
            rowsName = new String[]{"序号", "零件编码", "零件名称", "零件分类", priceColumnName,
                    "标准价", "指定价格方案", "价格方案", "折扣价格方案"};
        } else {
            rowsName = new String[]{"序号", "零件编码", "零件名称", "零件分类", priceColumnName,
                    "标准价", "指定价格方案", "折扣价格方案"};
        }
        List<Object[]> dataList = new ArrayList<>();
        int i = 1;

        PageHelperPlus.startPage(0, 60000, "w.CREATE_DATE DESC");
        List<MaterialsVO> materialsVOList = priMaterialsMapper.exportList(condition);
        for (MaterialsVO model : materialsVOList) {
            takeDecimals(model);
            getPriceSchemeRateDesc(condition, model);
            Object[] objs = new Object[rowsName.length];
            objs[0] = i;
            objs[1] = model.getMaterialsNo();
            objs[2] = model.getMaterialsDes();
            objs[3] = model.getMaterialsType();
            objs[4] = model.getPrice();
            objs[5] = model.getStandardPrice();
            objs[6] = model.getPriceSchemeDesc();
            if (StringUtils.isNotBlank(priceScheme)) {
                objs[7] = priceScheme;
                objs[8] = model.getModelRateDesc();
            } else {
                objs[7] = model.getModelRateDesc();
            }
            dataList.add(objs);
            i = ++i;
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    private void getPriceSchemeRateDesc(MaterialsSearchVO condition, MaterialsVO model) {
        if(model.getModelRateDesc() == null){
            model.setModelRateDesc("");
        }
        if(model.getPriceSchemeDesc() == null){
            model.setPriceSchemeDesc("");
        }

        if (StringUtils.isNotBlank(condition.getPriceScheme())) {
            if (StringUtils.isNotBlank(model.getModeRate())){
                model.setModelRateDesc(removeStringZero(model.getModeRate()));
            }
            if (StringUtils.isNotBlank(model.getMarketPrice())){
                model.setPriceSchemeDesc(removeStringZero(model.getMarketPrice()));
            }
            return;
        }

        if(StringUtils.isNotBlank(model.getModeType())){
            String[] arrModeType = model.getModeType().split(",");
            String[] arrPriceGroup = model.getPriceGroup().split(",");
            String[] arrModeRate = model.getModeRate().split(",");
            String[] arrMarketPrice = model.getMarketPrice().split(",");
            for (int i=0; i < arrModeType.length ; i++){
                if ("0".equals(arrModeType[i])){
                    model.setModelRateDesc(model.getModelRateDesc() + arrPriceGroup[i] + ":" + arrModeRate[i] + ";");
                }
                if ("1".equals(arrModeType[i])){
                    model.setPriceSchemeDesc(model.getPriceSchemeDesc() + arrPriceGroup[i] + ":" + arrMarketPrice[i] + "元;");
                }
            }
        }
    }

    private String removeStringZero(String cond) {
        return Arrays.stream(cond.split(",")).filter(x->!"0".equals(x)).collect(Collectors.joining(","));
    }

    /**
     * 导入价格方案零件
     *
     * @param in
     * @param orgId
     * @param activityId
     * @return
     * @throws Exception
     */
    @Transactional
    public FunctionResult importFormExcel(InputStream in, String orgId, String activityId) throws Exception{
        FunctionResult result=new FunctionResult();

        if (StringUtils.isBlank(activityId)) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("该价格方案不存在");
            return result;
        }
        MarketingActivityDO marketingActivity = marketingActivityMapper.item(activityId);

        if (null == marketingActivity) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("该价格方案不存在");
            return result;
        }

        HSSFWorkbook wb=new HSSFWorkbook(in);
        HSSFSheet sheet=wb.getSheetAt(0);

        int totalRow=sheet.getLastRowNum();
        if(totalRow<2){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        if(totalRow>5001){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入数据过大");
            return result;
        }
        int totalCell=sheet.getRow(1).getLastCellNum();
        if(totalCell!=6){
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }

        for (int i = 2; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            if (curRow == null) {
                continue;
            }
            try {
                saveOrUpdateMaterials(curRow, marketingActivity, orgId, activityId);
            } catch (Exception e) {
                result.setCode(ErrorCode.IllegalArument);
                result.setValue(e.getMessage());
                return result;
            }
        }
        result.setCode(ErrorCode.Success);
        return result;
    }


    private void saveOrUpdateMaterials(HSSFRow curRow, MarketingActivityDO marketingActivity, String orgId, String activityId)
        throws Exception {
        FunctionResult result=new FunctionResult();
        // 序号
//        String no = getCellValue(curRow, 0);
        // 零件号
        String materialsNo = getCellValue(curRow, 1);
        if (StringUtils.isBlank(materialsNo)) {
            return;
        }
        // 如果是指定折扣的方案，价格为空
        BigDecimal price;
        if (MOTE_TYPE_RATE.equals(marketingActivity.getModeType())) {
            price = null;
        } else {
            String cellPrice = getCellValue(curRow, 4);
            if (StringUtils.isBlank(cellPrice)) {
                throw new Exception("零件号" + materialsNo +"价格不能为空");
            }
            try {
                price = DecimalUtil.roundDecimal4Enter(new BigDecimal(cellPrice));
            } catch (NumberFormatException e) {
                throw new Exception("零件号" + materialsNo + "价格请填写数字");
            }
        }
        boolean needDel = "是".equals(getCellValue(curRow, 5));
        String id = marketingMaterialsMapper.getIdByActivityMaterials(orgId, materialsNo, activityId);
        if(needDel){
            if(StringUtils.isNotBlank(id)){
                marketingMaterialsMapper.deleteByPrimaryKey(id);
            }
            return;
        }

        PriMaterialsDO materialsDO = priMaterialsMapper.itemByNo(materialsNo, orgId);
        if (null == materialsDO) {
            throw new Exception("零件" + materialsNo +"系统中不存在，请确认");
        }

        MarketingMaterialsDO marketingMaterialsDO = new MarketingMaterialsDO();
        Date system = new Date();
        marketingMaterialsDO.setUpdateDate(system);
        marketingMaterialsDO.setPrice(price);
        marketingMaterialsDO.setMaterialsDes(materialsDO.getMaterialsDes());
        if (StringUtils.isBlank(id)) {
            // save
            ActionResult<String> textResult = fastGenClient.textGuid();
            marketingMaterialsDO.setId(textResult.getValue());
            marketingMaterialsDO.setActivityId(activityId);
            marketingMaterialsDO.setOrgId(orgId);
            marketingMaterialsDO.setMaterialsNo(materialsNo);
            marketingMaterialsDO.setCreateDate(system);
            marketingMaterialsMapper.insert(marketingMaterialsDO);
        } else {
            //update
            marketingMaterialsDO.setId(id);
            marketingMaterialsMapper.update(marketingMaterialsDO);
        }
    }

    private String getCellValue(HSSFRow curRow, int i){
        HSSFCell cell = curRow.getCell(i);
        if (null == cell) {
            return StringUtils.EMPTY;
        }
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue();
    }

    /**
     * 下载价格方案批量导入零件模板
     *
     * @throws Exception
     */
    public void download() throws Exception{
        FileUtil.downLoadFile(response, filePath, MARKET_MATERIALS_TEMPLATE_FILE);
    }

    public ErrorCode batchSaveDealer(MarketingDealerAddVO marketingDealerAddVO, String orgId) {
        List<String> activityIdList = marketingDealerAddVO.getActivityIdList();
        for (String activityId : activityIdList){
            CompanyDealerVO companyDealerVO = new CompanyDealerVO();
            companyDealerVO.setActiveId(activityId);
            companyDealerVO.setOrgId(orgId);
            List<CompanyDealerDO> companyDealerDOList = companyDealerMapper.listForPriceScheme(companyDealerVO);
            for (CompanyDealerDO companyDealerDO : companyDealerDOList){
                String dealerOrgId = companyDealerDO.getDealerOrgId();
                Integer presenceCount = marketingDealerMapper.checkPresenceCount(activityId, dealerOrgId);
                if (presenceCount > 0){
                    continue;
                }
                ActionResult<String> textResult = fastGenClient.textGuid();
                if (textResult.getCode() != ErrorCode.Success.getCode()) {
                    return ErrorCode.IllegalArument;
                }
                MarketingDealerDO marketingDealerDO = new MarketingDealerDO();
                marketingDealerDO.setId(textResult.getValue());
                marketingDealerDO.setActivityId(activityId);
                marketingDealerDO.setDealerOrgId(dealerOrgId);
                marketingDealerDO.setDealerOrgName(companyDealerDO.getCompanyName());
                marketingDealerDO.setCreateDate(new Date());
                marketingDealerDO.setOrgId(orgId);
                marketingDealerMapper.insert(marketingDealerDO);
            }
        }
        return ErrorCode.Success;
    }

    public ErrorCode batchRemoveDealer(MarketingDealerAddVO marketingDealerAddVO, String orgId) {
        List<String> activityIdList = marketingDealerAddVO.getActivityIdList();
        for (String activityId : activityIdList){
            marketingDealerMapper.batchRemoveDealer(orgId,activityId);
        }
        return ErrorCode.Success;
    }

    /**
     * 获取代理商零售价
     * @param agentRetailPriceName
     * @param orgId
     * @param materialsNo
     * @return
     */
    public MarketingActivityPriceVO getAgentRetailPrice(String agentRetailPriceName, String orgId, String materialsNo){
            PriMaterialsDO priMaterialsDO=priMaterialsMapper.itemByNo(materialsNo,orgId);
            if(priMaterialsDO == null){
                return null;
            }
            MarketingActivityPriceVO info = marketingActivityMapper.getAgentRetailPrice(agentRetailPriceName,orgId,materialsNo);
            if (null == info){
                return null;
            }
            if(info.getModeType()==1){
                info.setDiscountPrice(info.getPrice());
            }else {
                BigDecimal disPrice=priMaterialsDO.getPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                disPrice=disPrice.multiply(info.getModeRate());
                info.setDiscountPrice(disPrice);
            }
            return info;
    }

    public PageCommonVO<SupplierPriceSchemeQueryResultVO> supplierPriceSchemeQuery(SearchCommonVO<SupplierPriceSchemeQeuryParamVO> condition){
        SupplierPriceSchemeQeuryParamVO queryParam = condition.getFilters();
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<SupplierPriceSchemeQueryResultVO> supplierPriceSchemeQueryResultVOS = marketingActivityMapper.supplierPriceSchemeQuery(queryParam);
        PageCommonVO<SupplierPriceSchemeQueryResultVO> result = new PageCommonVO<>();
        result.setPageInfo(new PageInfo(supplierPriceSchemeQueryResultVOS));
        result.setPageInfoList(supplierPriceSchemeQueryResultVOS);
        return result;
    }

    // 判断是否有权限
    public CompanyDealerDO itemByOrgId(String supplierOrgId, String orgId) {
        return companyDealerMapper.itemByOrgId(supplierOrgId, orgId);
    }

    public List<MarketingActivityDO> getPricePlan(String oemOrgId, String orgId) {
        return marketingActivityMapper.getPricePlan(oemOrgId, orgId);
    }

    public MarketingActivityDO item(String id) {
        return marketingActivityMapper.item(id);
    }

    public MarketingActivityDO itemValid(String id) {
        return marketingActivityMapper.itemValid(id);
    }


    public List<MarketingMaterialsVO> getMaterialsByActivityId(OemPriceSyncVO oemPriceSyncVO, String orgId, String oemOrgId, List<Integer> deviceTypes) {
        MarketingMaterialsConditionVO condition = new MarketingMaterialsConditionVO();
        condition.setOemOrgId(oemPriceSyncVO.getOemOrgId());
        condition.setActivityId(oemPriceSyncVO.getPricePlanId());
        condition.setOrgId(orgId);
        condition.setDeviceTypes(deviceTypes);
        return marketingMaterialsMapper.getMaterialsByActivityId(condition);
    }

    public List<MarketingMaterialsVO> getMaterialsPriceByActivityId(OemPriceSyncVO oemPriceSyncVO, String orgId, String oemOrgId, List<Integer> deviceTypes) {
        MarketingMaterialsConditionVO condition = new MarketingMaterialsConditionVO();
        condition.setOemOrgId(oemPriceSyncVO.getOemOrgId());
        condition.setActivityId(oemPriceSyncVO.getPricePlanId());
        condition.setOrgId(orgId);
        condition.setDeviceTypes(deviceTypes);
        return marketingMaterialsMapper.getMaterialsPriceByActivityId(condition);
    }

    public PageCommonVO priceSearchReportList(SearchCommonVO<PriceSearchReportDO> condition) {
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageCommonVO<PriceSearchReportDO> pageCommonVO = new PageCommonVO<>();

        String materialsNos = condition.getFilters().getMaterialsNos();

        if (!StringUtil.isNullOrEmpty(materialsNos)) {
            condition.getFilters().setMaterialsList(Arrays.asList(materialsNos.split(",")));
        }
        List<PriceSearchReportDO> list = marketingActivityMapper.priceSearchReportList(condition.getFilters());
        pageCommonVO.setPageInfo(new PageInfo<>(list));
        pageCommonVO.setPageInfoList(list);
        return pageCommonVO;
    }


    public void invokeExport(List<PriceSearchReportDO> reportDOS) throws Exception {
        String title = "价格查询导出";
        String[] rowsName = {"序号","工厂名称", "零件编码", "零件名称", "价格", "库存", "尺寸", "重量"};
        List<Object[]>  dataList = new ArrayList<>();
        Object[] objs;
        if(CollectionUtils.isEmpty(reportDOS)){
            ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
            exportUtil.export(response);
            return;
        }

        for (int i = 0; i < reportDOS.size(); i++) {
            objs = new Object[rowsName.length];
            PriceSearchReportDO reportDO = reportDOS.get(i);
            objs[0] = i+1;
            objs[1] = reportDO.getCompanyName();
            objs[2] = reportDO.getMaterialsNo();
            objs[3] = reportDO.getMaterialsDesc();
            objs[4] = reportDO.getPrice();
            objs[5] = reportDO.getAmount();
            objs[6] = reportDO.getWeight();
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }

    public void priceSearchExportAll(PriceSearchReportDO condition) throws Exception {
        //根据sap code取orgId
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(SAP_CODE);

        condition.setCurrentOrgId(companyInfoDO.getOrgId());
        String materialsNos = condition.getMaterialsNos();

        if (!StringUtil.isNullOrEmpty(materialsNos)) {
            condition.setMaterialsList(Arrays.asList(materialsNos.split(",")));
        }
        List<PriceSearchReportDO> list = marketingActivityMapper.priceSearchReportListForClient(condition);
        //对价格和图片路径进行处理
        processPriceImage(list);
        invokeExport(list);
    }

    private void processPriceImage(List<PriceSearchReportDO> list) {
        for (PriceSearchReportDO priceSearchReportDO : list) {
            //价格策略如果已启用
            if (priceSearchReportDO.getState() != null && priceSearchReportDO.getState() == 1) {
                //价格策略类型如果是固定折扣且折扣不为空
                if (priceSearchReportDO.getModeType() != null
                        && priceSearchReportDO.getModeType() == 0
                        && priceSearchReportDO.getModeRate() != null
                        && priceSearchReportDO.getBasicPrice() != null) {
                    //重新计算价格
                    BigDecimal discountPrice = priceSearchReportDO.getBasicPrice()
                            .divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP)
                            .multiply(priceSearchReportDO.getModeRate());
                    priceSearchReportDO.setPrice(discountPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                }

                //价格策略类型为指定价格
                if (priceSearchReportDO.getModeType() != null
                        && priceSearchReportDO.getModeType() == 1
                        && priceSearchReportDO.getPrice() != null) {
                    priceSearchReportDO.setPrice(priceSearchReportDO.getPrice().divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
                }
            }
            if (priceSearchReportDO.getOrgImageUrl() != null) {
                String[] urls = priceSearchReportDO.getOrgImageUrl().split(",");
                if (urls.length > 0) {
                    priceSearchReportDO.setOrgImageUrl(urls[0]);
                }
            }
            priceSearchReportDO.setBasicPrice(null);
        }
    }


    /**
     * 客户端价格查询报表
     * @param condition
     * @return
     */
    public PageCommonVO priceSearchReportListForClient(SearchCommonVO<PriceSearchReportDO> condition) {
        //根据sap code取orgId
        CompanyInfoDO companyInfoDO = companyInfoMapper.itemBySap(SAP_CODE);

        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        PageCommonVO<PriceSearchReportDO> pageCommonVO = new PageCommonVO<>();

        condition.getFilters().setCurrentOrgId(companyInfoDO.getOrgId());
        String materialsNos = condition.getFilters().getMaterialsNos();

        if (!StringUtil.isNullOrEmpty(materialsNos)) {
            condition.getFilters().setMaterialsList(Arrays.asList(materialsNos.split(",")));
        }
        List<PriceSearchReportDO> list = marketingActivityMapper.priceSearchReportListForClient(condition.getFilters());
        //对价格和图片路径进行处理
        processPriceImage(list);
        pageCommonVO.setPageInfo(new PageInfo<>(list));
        pageCommonVO.setPageInfoList(list);
        return pageCommonVO;
    }

    public Map<String, MarketingActivityPriceVO> queryYnPriceMap(List<MaterialsVO> resultList) {
        Map<String, MarketingActivityPriceVO> r = new HashMap<>();
        if (CollectionUtils.isEmpty(resultList)) {
            return r;
        }
        List<String> materialsNos = resultList.stream().filter(x -> StringUtils.isNotBlank(x.getMaterialsNo())).map(x -> x.getMaterialsNo()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(materialsNos)) {
            return r;
        }
        List<MarketingActivityPriceVO> l = marketingActivityMapper.queryYnPriceMap(materialsNos, companyUtil.ynOrgId());
        l.forEach(x -> {
            r.put(x.getMaterialsNo(), x);
        });
        return r;
    }

    public Map<String, BigDecimal> queryYnInventoryMap(List<MaterialsVO> resultList, String orgId) {
        Map<String, BigDecimal> r = new HashMap<>();
        if (CollectionUtils.isEmpty(resultList)) {
            return r;
        }
        if (StringUtils.isBlank(orgId)) {
            orgId = resultList.get(0).getOrgId();
        }
        if (!companyUtil.isYN(orgId)) {
            return r;
        }
        List<String> materialsNos = resultList.stream().filter(x -> StringUtils.isNotBlank(x.getMaterialsNo())).map(x -> x.getMaterialsNo()).collect(Collectors.toList());
        return  doQueryYnInventoryMap(materialsNos);
    }

    public Map<String, BigDecimal> queryYnInventoryMapByMaterials(List<String> materialsNos, String orgId) {
        Map<String, BigDecimal> r = new HashMap<>();
        if (!companyUtil.isYN(orgId)) {
            return r;
        }
        if (CollectionUtils.isEmpty(materialsNos)) {
            return r;
        }
        return  doQueryYnInventoryMap(materialsNos);
    }

    public Map<String, BigDecimal> doQueryYnInventoryMap(List<String> materialsNos) {
        Map<String, BigDecimal> r = new HashMap<>();
        if (CollectionUtils.isEmpty(materialsNos)) {
            return r;
        }
//        try {
//            ActionResult<Map<String, YnInventoryVO>> rsp = erpSyncClient.queryYnInventoryMapByCodes(materialsNos);
//            if (null != rsp && MapUtils.isNotEmpty(rsp.getValue())) {
//                for (Map.Entry<String, YnInventoryVO> en : rsp.getValue().entrySet())
//                    if (null != en && null != en.getValue()) {
//                        r.put(en.getKey(), en.getValue().getCurquanbalance());
//                    }
//                return r;
//            }
//        } catch (Exception e) {
//            log.error("", e);
//        }
        return r;
    }
}
